//
//  GDOauthViewController.swift
//  weibo
//
//  Created by user on 15/11/24.
//  Copyright © 2015年 user. All rights reserved.
//

import UIKit

import SVProgressHUD

class GDOauthViewController: UIViewController {
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        
        //加载授权界面
        let request = NSURLRequest(URL: GDNetworkTool.sharedInstance.oauthURL())
        
        webView.loadRequest(request)
        
        // 设置导航栏
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    /// 填充账号
    func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='13697754467'; document.getElementById('passwd').value='622848';"
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //加载accessToken
    func loadAccessToken(code: String) {
        //发送网络请求
        GDNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            //判断是否有错误
            //测试出错得清况
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("你的网络不给力...", maskType: SVProgressHUDMaskType.Black)
                
                //延时1s
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                
                return
            }
            //没有出错，保存数据
            //创建模型
            let userAccount = GDUserAccount(dict: result!)
            
            //保存对象
            userAccount.saveAccout()
//            print("userAccount:\(userAccount)")
            
            self.close()
            
            //切换界面
//            (UIApplication.sharedApplication().delegate as? AppDelegate)?.window?.rootViewController = GDMainViewController()
            AppDelegate.switchRootViewController(false)
            
        }
    }

    /// 关闭控制器
    func close() {
        // 关闭SV
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    private lazy var webView = UIWebView()
}


extension GDOauthViewController: UIWebViewDelegate {
    /// webView开始加载链接
    func webViewDidStartLoad(webView: UIWebView) {
        // showWithStatus只有没有主动关闭,一直显示
        // showInfoWithStatus 过段时间就消失
        SVProgressHUD.showWithStatus("正在载入...", maskType: SVProgressHUDMaskType.Black)
    }
    
    /// webView加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    
    //webView加载链接
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        //当用户点击取消或同意，拦截，不让它加载，我们来处理
        if !urlString.hasPrefix(GDNetworkTool.sharedInstance.redirect_uri ){
            //其他情况，直接加载
            return true
        }
        
        // 点击取消 或 点击授权
        // 判断url地址里面是以code=开头,截取code= 后面的字符串
        if let query = request.URL?.query{
            let codeString = "code="
            // 判断是否是以code=开头
            if query.hasPrefix(codeString){
                // 点击授权, 截取code的值
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code:\(code)")
                //加载accessToken
                loadAccessToken(code)
            }else{
                //点击取消
                self.close()
            }
        }
        //不去加载授权回调地址
        return false
    }
    
}
